package com.example.my_isc_nirscan.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.my_isc_nirscan.R;
import com.example.my_isc_nirscan.adapter.DeviceListAdapter;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class TestBluetoothActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_BLUETOOTH_CONNECT = 1001;
    private static final int REQUEST_ENABLE_BT = 1002;
    private static final int REQUEST_DISABLE_BT = 1003 ;

    private RelativeLayout rlTitle;
    private Switch ckBluetooth;
    private TextView tvDiscovery;
    private ListView lvBluetooth;
    private Button btSearch;
    private Button btPair;
    private Button btConnect;
    private Button btCancel;

    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();
    // 通常继承自BaseAdapter或ArrayAdapter,用于显示蓝牙设备列表
    private DeviceListAdapter deviceAdapter;
    private BluetoothDevice currentDevice;

    Map<BluetoothDevice, Integer> deviceRssiMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        // 获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图
        initView();
        // 设置监听器
        setListeners();
        // 初始化蓝牙列表
        initBluetoothList();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        rlTitle = findViewById(R.id.rl_title);
        ckBluetooth = findViewById(R.id.ck_bluetooth);
        tvDiscovery = findViewById(R.id.tv_discovery);
        lvBluetooth = findViewById(R.id.lv_bluetooth);
        btSearch = findViewById(R.id.bt_search);
        btPair = findViewById(R.id.bt_pair);
        btConnect = findViewById(R.id.bt_connect);
        btCancel = findViewById(R.id.bt_cancel);

        // 设置蓝牙开关初始状态
        if (ckBluetooth != null) {
            ckBluetooth.setChecked(bluetoothAdapter.isEnabled());
        }
    }

    private void initBluetoothList() {
        deviceAdapter = new DeviceListAdapter(this, deviceRssiMap);
        lvBluetooth.setAdapter(deviceAdapter);
        // 设置蓝牙列表点击事件
//        lvBluetooth.setOnItemClickListener((parent, view, position, id) -> {
//            currentDevice = deviceList.get(position);
//        });
    }

    private void setListeners() {
        // 蓝牙开关监听
        ckBluetooth.setOnCheckedChangeListener((buttonView, isChecked) -> {
            System.err.println("蓝牙开关状态：" + isChecked);
            if(isChecked) {
                enableBluetooth();
            } else {
                disableBluetooth();
            }
        });

        // 搜索按钮点击监听
        btSearch.setOnClickListener(v -> {
            searchBluetoothDevices();
        });

        // 配对按钮点击监听
        btPair.setOnClickListener(v -> {
            if (currentDevice != null) {
                pairDevice(currentDevice);
            } else {
                Toast.makeText(this, "请先选择设备", Toast.LENGTH_SHORT).show();
            }
        });

        // 连接按钮点击监听
        btConnect.setOnClickListener(v -> {
            if (currentDevice != null) {
                connectDevice(currentDevice);
            } else {
                Toast.makeText(this, "请先选择设备", Toast.LENGTH_SHORT).show();
            }
        });

        // 取消配对按钮点击监听
        btCancel.setOnClickListener(v -> {
            if (currentDevice != null) {
                cancelPairing(currentDevice);
            } else {
                Toast.makeText(this, "请先选择设备", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 启用蓝牙
    private void enableBluetooth() {
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    // 禁用蓝牙
    private void disableBluetooth() {
        if (bluetoothAdapter.isEnabled()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_CODE_BLUETOOTH_CONNECT);
                return;
            }
            // 发送意图让用户手动关闭蓝牙，下面这个api已经不支持了
            // Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISABLE);

            // 所以使用ACTION_BLUETOOTH_SETTINGS 来引导用户到蓝牙设置界面，让他们在那里手动关闭蓝牙
            Intent disableBtIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);

            startActivityForResult(disableBtIntent, REQUEST_DISABLE_BT);
        }
    }


    // 搜索蓝牙设备
    private void searchBluetoothDevices() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
//        registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

        // 清空设备列表
        deviceList.clear();
        deviceAdapter.notifyDataSetChanged();

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(discoveryReceiver, filter);

        // 开始搜索
        bluetoothAdapter.startDiscovery();
        tvDiscovery.setText("正在搜索...");
    }

    // 配对设备
    private void pairDevice(BluetoothDevice device) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            try {
                Method method = device.getClass().getMethod("createBond", (Class[]) null);
                method.invoke(device, (Object[]) null);
                Toast.makeText(this, "正在配对...", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "配对失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "设备已配对", Toast.LENGTH_SHORT).show();
        }
    }

    // 连接设备
    private void connectDevice(BluetoothDevice device) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            // 创建蓝牙Socket连接
            try {
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                socket.connect();
                Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "请先配对设备", Toast.LENGTH_SHORT).show();
        }
    }

    // 取消配对
    private void cancelPairing(BluetoothDevice device) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            try {
                Method method = device.getClass().getMethod("removeBond", (Class[]) null);
                method.invoke(device, (Object[]) null);
                Toast.makeText(this, "已取消配对", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "取消配对失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 广播接收器
    private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 获取 RSSI 值
                int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                // 创建一个设备对象，包含 RSSI 信息
                System.err.println(device);
//                DeviceInfo deviceInfo = new DeviceInfo(device, rssi);

                System.err.println(deviceRssiMap);

                if (!deviceList.contains(device)) {
//                    deviceList.add(device);
                    // 更新Map中的RSSI值
                    deviceRssiMap.put(device, rssi);
                    deviceAdapter.notifyDataSetChanged();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                tvDiscovery.setText("搜索完成");
                unregisterReceiver(this);
            }
        }
    };

    // 设备信息类，用于存储 BluetoothDevice 和 RSSI
    public class DeviceInfo {
        BluetoothDevice device;
        int rssi;

        public DeviceInfo(BluetoothDevice device, int rssi) {
            this.device = device;
            this.rssi = rssi;
        }

        @Override
        public String toString() {
            return "DeviceInfo{" +
                    "device=" + device +
                    ", rssi=" + rssi +
                    '}';
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止搜索
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        // 注销广播接收器
        try {
            unregisterReceiver(discoveryReceiver);
        } catch (IllegalArgumentException e) {
            // 接收器可能未注册
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已启用", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "蓝牙启用失败", Toast.LENGTH_SHORT).show();
                ckBluetooth.setChecked(false);
            }
        }
    }

    // 下面这两块函数都没用到

    /**
     * 注册一个广播接收器来监听蓝牙状态的变化，确保在蓝牙完全禁用后再进行后续操作-----没用到
     */
    private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                if (state == BluetoothAdapter.STATE_OFF) {
                    // 蓝牙已禁用，可以在这里处理后续逻辑
                    Log.d("Bluetooth", "Bluetooth is now disabled");
//                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_BLUETOOTH_CONNECT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以继续关闭蓝牙
                disableBluetooth();
            } else {
                // 权限被拒绝，可以在这里处理，例如提示用户
            }
        }
    }
}
